package com.jimmyhsu.ecnudaowei.verify;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.jimmyhsu.ecnudaowei.Db.User;
import com.jimmyhsu.ecnudaowei.Db.UserInfoProvider;
import com.jimmyhsu.ecnudaowei.MyApplication;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.Utils.EcnuUtils;
import com.jimmyhsu.ecnudaowei.Utils.PreferenceUtils;
import com.jimmyhsu.ecnudaowei.login.LoginActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by jimmyhsu on 2017/3/1.
 */

public class SchoolVerifyActivity extends AppCompatActivity implements EcnuUtils.OnVerifyListner {

    public static final String EXTRA_REAL_NAME = "extra_real_name";
    private static final String TAG = "SchoolVerifyActivity";
    private static final String PROMPT_EMPTY_ID = "学号不得为空";
    private static final String PROMPT_EMPTY_PASSWORD = "密码不得为空";
    private static final String PROMPT_EMPTY_CAPTCHA = "验证码不得为空";
    public static final String SP_REAL_NAME = "realName";
    public static final String SP_IDC_PASSWORD = "idcPassword";

    private String mUserName;
    private String mPassword;


    @BindView(R.id.id_verify_id)
    EditText mEdtId;

    @BindView(R.id.id_verify_password)
    EditText mEdtPassword;

    @BindView(R.id.id_verify_captcha)
    EditText mEdtCaptcha;

    @BindView(R.id.id_verify_captcha_img)
    ImageView mIvCaptcha;

    @BindView(R.id.id_verify_progress)
    RelativeLayout mProgress;

    private EcnuUtils mEcnuUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_school);
        ButterKnife.bind(this);
        mEcnuUtils = new EcnuUtils();
        mUserName = ((MyApplication) getApplicationContext()).getName();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mEcnuUtils.prepare(mIvCaptcha);
    }

    @OnClick(R.id.id_verify_captcha_img)
    public void refreshCaptcha(View captchaView) {
        mEcnuUtils.refreshCaptcha((ImageView) captchaView);
    }


    @OnClick(R.id.id_verify_verify)
    public void verify() {
        if (checkInput()) {
            mPassword = mEdtPassword.getText().toString();
            mEcnuUtils.verify(mEdtId.getText().toString(),
                    mPassword,
                    mEdtCaptcha.getText().toString(),
                    this);
        }
    }

    private boolean checkInput() {
        EditText focusView = null;
        String prompt = PROMPT_EMPTY_CAPTCHA;
        if (TextUtils.isEmpty(mEdtId.getText().toString())) {
            prompt = PROMPT_EMPTY_ID;
            focusView = mEdtId;
        } else if (TextUtils.isEmpty(mEdtPassword.getText().toString())) {
            prompt = PROMPT_EMPTY_PASSWORD;
            focusView = mEdtPassword;
        } else if (TextUtils.isEmpty(mEdtCaptcha.getText().toString())) {
            prompt = PROMPT_EMPTY_CAPTCHA;
            focusView = mEdtCaptcha;
        }
        if (focusView != null) {
            focusView.setError(prompt);
            focusView.requestFocus();
            return false;
        } else {
            mProgress.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onVerify(boolean isValid, String studentName, EcnuUtils.USER_TYPE type, Bitmap avatar) {
        mProgress.setVisibility(View.GONE);
        if (isValid) {
            saveAndGoBack(mEdtId.getText().toString(), studentName);
        } else {
            verifyFail();
        }
    }

    private void verifyFail() {
        Snackbar.make(mEdtId, "验证失败！", Snackbar.LENGTH_SHORT).show();
    }

    private void saveAndGoBack(final String id, final String name) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(LoginActivity.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
        VerifyResultService verifyResultService = retrofit.create(VerifyResultService.class);
        Call<String> call = verifyResultService.uploadVerifyResult(id, name, mUserName, LoginActivity.getAndroidId(this));
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.body().equals("success")) {
                    PreferenceUtils.addToPreference(LoginActivity.SP_NAME, SchoolVerifyActivity.this,
                            SP_REAL_NAME, name);
                    PreferenceUtils.addToPreference(LoginActivity.SP_NAME, SchoolVerifyActivity.this,
                            SP_IDC_PASSWORD, mPassword);
                    Intent intent = new Intent();
                    intent.putExtra(EXTRA_REAL_NAME, name);
                    setResult(RESULT_OK, intent);
                    ContentResolver cr = getContentResolver();
                    ContentValues values = new ContentValues();
                    values.put(User.COL_VERIFIED, 1);
                    values.put(User.COL_REALNAME, name);
                    values.put(User.COL_STU_ID, id);
                    cr.update(UserInfoProvider.URI_USER_CURRENT, values, "_id=?", new String[]{"1"});
                    finish();
                } else {
                    Log.e(TAG, response.body());
                    mEcnuUtils.prepare(mIvCaptcha);
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                verifyFail();
                Log.e(TAG, "upload info failed");
                mEcnuUtils.prepare(mIvCaptcha);
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
        finish();
    }

    public static void startActivity(Activity context, int requestCode) {
        Intent intent = new Intent(context, SchoolVerifyActivity.class);
        context.startActivityForResult(intent, requestCode);
    }
}
